//
//  MZCaptchaButton.m
//  meizhuang
//
//  Created by sky on 16/9/6.
//  Copyright © 2016年 netease. All rights reserved.
//

#import "WFCaptchaButton.h"
#import <BlocksKit/NSTimer+BlocksKit.h>

static NSTimeInterval __mzCaptchaStartSeconds;

#define kCaptchaCountDownSeconds 60

@implementation WFCaptchaButton

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _normalText = @"获取验证码";
        _coolDownTextFormat = @"剩余%.0f";
        self.titleLabel.font =  SCFont(13);
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.backgroundColor = [UIColor themeColor];
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        [self addTarget:self action:@selector(__mzOnCaptcha) forControlEvents:UIControlEventTouchUpInside];
        [self updateCaptchaState];
    }
    return self;
}

- (void)dealloc {
    [_coolDownTimer invalidate];
    _coolDownTimer = nil;
}

- (void)__mzOnCaptcha {
    if (!self.enabled) {
        return;
    }
    [self startCoolDown];
}

- (void)startCoolDown {
    NSTimeInterval currentSeconds = [[NSDate date] timeIntervalSince1970];
    __mzCaptchaStartSeconds = currentSeconds;
    [self updateCaptchaState];
}

- (void)resetCoolDown {
    __mzCaptchaStartSeconds = 0;
    self.enabled = YES;
    [self setTitle:_normalText forState:UIControlStateNormal];
    if (_coolDownTimer) {
        [_coolDownTimer invalidate];
        _coolDownTimer = nil;
    }
}

+ (void)resetCoolDown {
    __mzCaptchaStartSeconds = 0;
}

- (void)updateCaptchaState {
    NSTimeInterval currentSeconds = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval seconds = currentSeconds - __mzCaptchaStartSeconds;
    NSTimeInterval remainSeconds = kCaptchaCountDownSeconds - seconds;
    if (remainSeconds <= 0) {
        [self resetCoolDown];
    }else {
        self.enabled = NO;
        @weakify(self)
        if (!_coolDownTimer) {
            _coolDownTimer = [NSTimer bk_scheduledTimerWithTimeInterval:1 block:^(NSTimer *timer) {
                @strongify(self)
                [self updateCaptchaState];
            } repeats:YES];
        }
        [self setTitle:[NSString stringWithFormat:_coolDownTextFormat,remainSeconds] forState:UIControlStateDisabled];
    }
}


@end
